#-*-coding:utf-8-*-
__author__ = 'toriycn'

import json
import time
import threading
from app.utils import SSHUtil

from app.monitors import redishelper
from app.monitors.server.conf import settings,hosts
from app.monitors.server.core.serialize import MontorDataDual,AlertDataDual

'''
   MOnitor server:
        supply base server
'''
class MonitorServer(object):

    '''
       初始化
    '''
    def __init__(self):
        self.r = redishelper.RedisHelper(settings.RedisServer,settings.RedisPort,settings.RedisPubChannel,settings.RedisSubChannel)
        self.alertR = redishelper.RedisHelper(settings.RedisServer,settings.RedisPort,settings.RedisAlertChannel,settings.RedisAlertChannel)
        self.hostTemplate = hosts.HostConfig(self)
        self.serialize = MontorDataDual(self)
        self.alertserialize =AlertDataDual(self)
        self.save_configs()
        self.reloadFlag = True
        self.host_config_dic = {}


    def reloadConfig(self):
        self.hostTemplate.reloadConfig()
        #将数据重新写入redis中
        self.save_configs()

    #系统启动命令，开始执行命令
    def start(self):
        self.data_handle()
        self.alert_handle()
        #启动订阅，然后订阅从客户端发送的各种命令
        pub = self.r.subscribe()
        while True:
            #处理数据
            host_service_data = pub.parse_response()
            host_service_data = json.loads(str(host_service_data[2],encoding="utf-8"))
            host_service_data['time_stamp'] = time.time()
            service_data_key = settings.REDIS_KEY_TEMPLATE %(host_service_data['host'],
                                                       host_service_data['service'])
            self.r.set(service_data_key,json.dumps(host_service_data))

    #保存配置信息
    def save_configs(self):
        self.serialize.push_all_configs_into_redis(self.hostTemplate.getMointorTemplate())

    #数据处理
    def data_handle(self):
        '处理监控数据,独立线程，并发的'
        self.serialize.setDaemon(True)
        self.serialize.start()

    #报警
    def alert_handle(self):
        '处理告警信息，独立线程'
        self.alertserialize.setDaemon(True)
        self.alertserialize.start()

    #获取所有的配置信息
    def fetch_all_configs(self):
        if self.reloadFlag:
            host_groups = self.hostTemplate.getMointorTemplate()
            #遍历主机组
            for group in host_groups:
                #打印组名
                for hosts in group.hosts:
                    #如果主机不在，生成一个主机
                    if hosts not in self.host_config_dic.keys():
                        self.host_config_dic[hosts] = {}
                    #遍历服务名
                    for s in group.services:
                        s = self.hostTemplate.getService(s)
                        self.host_config_dic[hosts][s.name]= s
            self.reloadFlag = False
            return self.host_config_dic
        else:
            return self.host_config_dic

    def config_hosttemplate(self):
        pass

    def getServiceReal(self,hostip,sname,strigger):
           service_date_redisKey = settings.REDIS_KEY_TEMPLATE_HIS_DATA %\
                                    (hostip,sname,strigger)
           print(service_date_redisKey)
           valueinfo = self.r.get(service_date_redisKey)
           if valueinfo is None or valueinfo == '':
              valueinfo = {}
           else:
              valueinfo = eval(valueinfo)
           #这是一个tuple
           realvalueinfo = valueinfo.get("real",[])
           Value = 0
           if len(realvalueinfo) >0:
               Value = int(realvalueinfo[0][1])

           return Value

    def getClollectionHostInfo(self,hostip):

        hostInfo = {"hostname":"测试一",
                "OS":"mac os",
                "MEM_SIZE":"64G",
                "CPU_SIZE":"CORE",
                "DB_SIZE":"256G"}
        cmd  =["hostname","uname -a","awk '/MemTotal/{total=$2}/MemFree/{free=$2}END{print (total)/1024}'  /proc/meminfo",
                "grep 'model name' /proc/cpuinfo |uniq |awk -F : '{print $2}' |sed 's/^[ \t]*//g' |sed 's/ \+/ /g'",
                "fdisk -l |grep 'Disk' |awk -F , '{print $1}' | sed 's/Disk identifier.*//g' | sed '/^$/d'"]

        hostKey = settings.REDIS_KEY_HOSTINFO % hostip
        hostinRedis = self.r.get(hostKey)
        if hostinRedis is None or hostinRedis == '':
            return {}
        else:
            hostinRedis = eval(hostinRedis)

        print(hostinRedis)
        collectionValue = SSHUtil.ssh2(hostip,hostinRedis.get("username",settings.SERVERUSER),
                                       hostinRedis.get("password",settings.SERVERPASSWD),cmd)
        print(collectionValue)

        for inx,val in zip(range(5),collectionValue.split("<br>")):
            if inx == 0:
                hostInfo["hostname"] = val
            if inx == 1:
                hostInfo["OS"] = val
            if inx == 2:
                hostInfo["MEM_SIZE"] = val
            if inx == 3:
                hostInfo["CPU_SIZE"] = val
            if inx == 4:
                hostInfo["DB_SIZE"] = val

        hostinRedis.update(hostInfo)

        self.r.set(hostKey,hostinRedis)
        return hostinRedis


if __name__ == "__main__":
        cmd  =["hostname","uname -a","awk '/MemTotal/{total=$2}/MemFree/{free=$2}END{print (total)/1024}'  /proc/meminfo",
                "grep 'model name' /proc/cpuinfo |uniq |awk -F : '{print $2}' |sed 's/^[ \t]*//g' |sed 's/ \+/ /g'",
                "fdisk -l |grep 'Disk' |awk -F , '{print $1}' | sed 's/Disk identifier.*//g' | sed '/^$/d'"]
        hostip = "123.57.154.30"
        print(SSHUtil.ssh2(hostip,settings.SERVERUSER,settings.SERVERPASSWD,cmd))
        cmd  =["uname -a"]
        hostip = "123.57.154.30"
        print(SSHUtil.ssh2(hostip,settings.SERVERUSER,settings.SERVERPASSWD,cmd))
